package site.addzero.repl

import kotlinx.coroutines.runBlocking
import org.koin.core.annotation.Single
import site.addzero.app.AdvancedRepl
import site.addzero.app.ParamDef
import site.addzero.cli.config.configService
import site.addzero.cli.dotfiles.sync_stragty.SyncUtil
import site.addzero.util.KoinInjector.inject
import site.addzero.util.StatusPrinter
import kotlin.reflect.typeOf

/**
 * AddPkgCommand的REPL包装类，实现AdvancedRepl接口
 */
@Single

class RmPkgRepl : AdvancedRepl<RmPkgRepl.AddPkgCommandParams, Unit> {
    override val command: String = "rm-pkg"
    override val description: String
        get() = "删除软件包"
    override val paramDefs: List<ParamDef> = listOf(
        ParamDef(
            name = "packageNames",
            type = typeOf<String>(),
            description = "软件包名称(多个软件包用逗号分隔)",
        )
    )

    data class AddPkgCommandParams(
        val packageNames: String
    )

    override fun eval(params: AddPkgCommandParams): Unit = runBlocking {
        val packageNames = params.packageNames.split(",").map { it.trim() }.filter { it.isNotEmpty() }

        if (packageNames.isEmpty()) {
            System.err.println("未提供有效的软件包名称")
            return@runBlocking
        }

        var successCount = 0
        for (packageName in packageNames) {
            val rmPkg = configService.rmPkg(packageName)
            if (rmPkg) {
                println("已删除软件包: $packageName")
                successCount++
            } else {
                System.err.println("删除软件包出错: $packageName")
            }
        }

        if (successCount > 0) {
            // 上传配置
            SyncUtil.commitAndPush()
            println("成功删除 $successCount 个软件包")
        } else {
            System.err.println("未能成功删除任何软件包")
        }

        // 打印当前的软连接和同步软件包信息
        val statusPrinter = inject<StatusPrinter>()
        statusPrinter.printCurrentStatus()
    }

//    override fun createParams(values: List<Any?>): AddPkgCommandParams {
//        return AddPkgCommandParams(
//            packageNames = values[0] as String
//        )
//    }
}
